#include <time.h>
#include <stdlib.h>
#include "PickupSprite.h"
#include "include.h"

PickupSprite::PickupSprite(TextureManager * textureManager, char * filename, Vector2D * textureVertices, Vector2D position, Vector2D size, float lifespan, int spriteId)
:Sprite(position, size, size, lifespan, textureManager, filename)
{
	this->spriteId = spriteId;
	this->textureVertices = textureVertices;
	int * frameSequence = (int*)malloc(sizeof(int)*9);
	//for(int i  = 0; i < 9; i++)
	//	frameSequence[i] = i;
	int startFrame = (int)(rand()/(double)RAND_MAX * 8);
	frameSequence[0] = startFrame;
	frameSequence[1] = (startFrame+1)%9;
	frameSequence[2] = (startFrame+2)%9;
	frameSequence[3] = (startFrame+6)%9;
	frameSequence[4] = (startFrame+7)%9;
	frameSequence[5] = (startFrame+8)%9;
	frameSequence[6] = (startFrame+5)%9;
	frameSequence[7] = (startFrame+4)%9;
	frameSequence[8] = (startFrame+3)%9;
	
	animationManager = new AnimationManager(0.03, frameSequence, 9, 3, 3);
	if(textureManager)
	{
		if(!(textureManager->LoadTexture(SPARKLE_TEXTURE)))
			printf("Error loading texture %s\n", SPARKLE_TEXTURE);
		animationIndex = textureManager->TextureIndex(SPARKLE_TEXTURE);	
	}
}
PickupSprite::~PickupSprite()
{
}
void PickupSprite::Think(double elapsedTime)
{
	animationManager->AddElapsedTime(elapsedTime);
}
bool PickupSprite::Collide(Object * object2, double elapsedTime)
{
	return false;
}
void PickupSprite::SpriteDrawEntryPoint()
{
	glPushMatrix();
	glLoadIdentity();
	glTranslatef(position.x,position.y, 0.0);
	float time = (float) clock();
	Vector2D size = startSize + sizeDelta * (time - birthTime)/(float)CLOCKS_PER_SEC;
	if(textureManager)
		textureManager->EnableTexture(animationIndex);
	glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
	glAlphaFunc( GL_GREATER, 0.01 );
  	glEnable( GL_ALPHA_TEST );
	glEnable(GL_TEXTURE_2D);
	//glBlendFunc(GL_SRC_COLOR, GL_DST_COLOR);
	//glBlendFunc(GL_ONE, GL_ONE);
	//glBlendFunc(GL_ONE_MINUS_SRC_ALPHA,GL_SRC_ALPHA);
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);
	glColor4f(1,1,1,0.9);
	glBegin(GL_POLYGON);
	Vector2D * texVertices = animationManager->GetVertices();
	Vector2D vertices[4] = {Vector2D(-size.x * 0.9, size.y * 0.9),
							Vector2D(size.x * 0.9,  size.y * 0.9),
							Vector2D(size.x * 0.9,  -size.y * 0.9),
							Vector2D(-size.x * 0.9, -size.y * 0.9)};
	
	for(int i=0; i < 4; i++)
	{	
		glTexCoord2f(texVertices[i].x, texVertices[i].y);
		glVertex2f(vertices[i].x, vertices[i].y);
	}
	glEnd();
	glPopMatrix();
	glDisable(GL_TEXTURE_2D);
	glDisable(GL_BLEND);
	delete(texVertices);
	texVertices = NULL;
}
